package edu.whu.controller;

import edu.whu.bean.Supplier;
import edu.whu.dao.SupplierMapper;
import edu.whu.exception.ExceptionResponse;
import edu.whu.exception.ProductException;
import edu.whu.service.SupplierService;
import edu.whu.service.impl.SupplierServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/supplier")
public class SupplierController {
    private final SupplierService service;
    @Autowired
    public SupplierController(SupplierMapper mapper) {
        this.service = new SupplierServiceImpl(mapper);
    }

    @GetMapping("/select")
    public Supplier select(int id){
        return service.selectById(id);
    }

    @GetMapping("/select/all")
    public List<Supplier> selectByProductId(){
        return service.selectAll();
    }

    @GetMapping("/add")
    public int insert(Integer id, String name, Integer productId){
        return service.insert(new Supplier(id,name,productId));
    }

    @GetMapping("/delete")
    public ResponseEntity<Object> delete(int id){
        try {
            service.delete(id);
            return ResponseEntity.ok().build();
        } catch (ProductException e) {
            ExceptionResponse response = new ExceptionResponse();
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
    }

    @GetMapping("/delete/productId")
    public ResponseEntity<Object> deleteByProductId(int id){
        try {
            service.deleteByProductId(id);
            return ResponseEntity.ok().build();
        } catch (ProductException e) {
            ExceptionResponse response = new ExceptionResponse();
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
    }
}
